<?php
namespace app\admin\controller;

use think\Db;
use app\admin\model\DepartmentModel;
use app\admin\model\DaytableModel;
use app\admin\model\MonthtableModel;
use app\admin\model\YeartableModel;
use app\admin\model\CapitaltableModel;
use app\admin\model\WebshoptableModel;
use app\admin\model\AssettableModel;

class Tablequery extends Base{

	#-< Common >----------------------------------------------------------------
	public function getDepartOpt() {
		$DepartModel = new DepartmentModel();
		$departs = $DepartModel->getCanSeeDepart(session('id'));
		$departs = $this->arr2tree($departs);
		$depart_opt = $this->getNameByTree($departs);
		return $depart_opt;
	}

	#-< Month >-----------------------------------------------------------------
	public function Month(){
		if($this->request->isPost()){
			$param = input('post.');
			$limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
			$where = [];
			if($param['seaDepart'] != ''){
				$where['depart_id'] = $param['seaDepart'];
			}
			if($param['seaTime'][0] != '' && $param['seaTime'][1] != ''){
				$param['seaTime'][0] = $param['seaTime'][0] / 1000;
				$param['seaTime'][1] = $param['seaTime'][1] / 1000;
				$where['rpt_date'] = ['between',$param['seaTime']];
			}
			if($param['seaLinkman'] != ""){
				$where['link_man'] = ['like',"%".$param['seaLinkman']."%"];
			}
			$monthModel = new MonthtableModel();
			$rows = $monthModel->getListRows($where,$offset,$limit);
			foreach($rows as $k => $v){
				$rows[$k]['rpt_date'] = date("Y年m月",$v['rpt_date']);
				$v['examine'] == 0 ? $rows[$k]['examine_name']="否" : $rows[$k]['examine_name']="是";
			}
			$total = $monthModel->getCount($where);
			return  ['code'=>1,'msg'=>'表格加载成功','data'=>[
				'rows' => $rows,'total'=>$total
			]];
		}
		$this->assign([
			'departs' => $this->getDepartOpt()
		]);
		return $this->fetch();
	}

	public function getForm(){
		$id = input('post.id');
		$ct = DB::name('table_month')->where('id',$id)->value('content');
		$form = $this->XML2Arr($ct);
		return ['code'=>1,'msg'=>'','data'=>$form];
	}

	public function monthEdit(){
		$this->assign([
			'id' => input("id")
		]);
		return $this->fetch('commit/edit_month');
	}

	public function monthDel(){
		$id = input('post.id');
		$info = DB::name('table_month')->where('id',$id)->find();
		if($info['is_commit'] == 1){
			return ['code'=> 0,'msg'=>'删除失败,已提交的报表不能删除'];
		}
		$res = DB::name('table_month')->where('id',$id)->delete();
		if($res !== false){
			return ['code'=> 1,'msg'=>'删除成功'];
		}else{
			return ['code'=> 0,'msg'=>'删除失败'];
		}
	}

	public function monthExamine(){
		$param = input('post.');
		$info = DB::name('table_month')->where('id',$param['id'])->find();
		if($info['is_commit'] == 1){
			return ['code'=> 0,'msg'=>'审核失败,已提交的报表不能审核'];
		}
		$user = DB::name('user')->where('id',session('id'))->value('real_name');
		$param['examine_man'] = $user;
		$res = DB::name('table_month')->where('id',$param['id'])->update($param);
		if($res !== false){
			return ['code'=>1,'msg'=>'审核成功'];
		}else{
			return ['code'=>0,'msg'=>'审核失败'];
		}
	}
	#-< Year >------------------------------------------------------------------
	public function Year() {
		if($this->request->isPost()){
			$param = input('post.');
			$limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
			$where = [];
			if($param['seaDepart'] != ''){
				$where['depart_id'] = $param['seaDepart'];
			}
			if($param['seaTime'][0] != '' && $param['seaTime'][1] != ''){
				$param['seaTime'][0] = $param['seaTime'][0] / 1000;
				$param['seaTime'][1] = $param['seaTime'][1] / 1000;
				$where['rpt_date'] = ['between',$param['seaTime']];
			}
			if($param['seaLinkman'] != ""){
				$where['link_man'] = ['like',"%".$param['seaLinkman']."%"];
			}
			$yearModel = new YeartableModel();
			$rows = $yearModel->getListRows($where,$offset,$limit);
			foreach($rows as $k => $v){
				$rows[$k]['rpt_date'] = date("Y",$v['rpt_date']);
				$v['examine'] == 0 ? $rows[$k]['examine_name']="否" : $rows[$k]['examine_name']="是";
			}
			$total = $yearModel->getCount($where);
			return  ['code'=>1,'msg'=>'表格加载成功','data'=>[
				'rows' => $rows,'total'=>$total
			]];
		}
		$this->assign([
			'departs' => $this->getDepartOpt()
		]);
		return $this->fetch();
	}

	public function yearDel(){
		$id = input('post.id');
		$info = DB::name('table_year')->where('id',$id)->find();
		if($info['is_commit'] == 1){
			return ['code'=> 0,'msg'=>'删除失败,已提交的报表不能删除'];
		}
		$res = DB::name('table_year')->where('id',$id)->delete();
		if($res !== false){
			return ['code'=> 1,'msg'=>'删除成功'];
		}else{
			return ['code'=> 0,'msg'=>'删除失败'];
		}
	}
	public function yearExamine(){
		$param = input('post.');
		$info = DB::name('table_year')->where('id',$param['id'])->find();
		if($info['is_commit'] == 1){
			return ['code'=> 0,'msg'=>'审核失败,已提交的报表不能审核'];
		}
		$user = DB::name('user')->where('id',session('id'))->value('real_name');
		$param['examine_man'] = $user;
		$res = DB::name('table_year')->where('id',$param['id'])->update($param);
		if($res !== false){
			return ['code'=>1,'msg'=>'审核成功'];
		}else{
			return ['code'=>0,'msg'=>'审核失败'];
		}
	}
	public function yearEdit() {
		$this->assign([
			'id' => input("id")
		]);
		return $this->fetch('commit/edit_year');
	}
	public function getForm_year() {
		$id = input('post.id');
		$ct = DB::name('table_year')->where('id',$id)->value('content');
		$form = $this->XML2Arr($ct);
		return ['code'=>1,'msg'=>'','data'=>$form];
	}
	#-< day >-------------------------------------------------------------------
	public function Day(){
		if($this->request->isPost()){
			$param = input('post.');
			$limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
			$where = [];
			if($param['seaDepart'] != ''){
				$where['depart_id'] = $param['seaDepart'];
			}
			if($param['seaTime'][0] != '' && $param['seaTime'][1] != ''){
				$param['seaTime'][0] = $param['seaTime'][0] / 1000;
				$param['seaTime'][1] = $param['seaTime'][1] / 1000;
				$where['rpt_date'] = ['between',$param['seaTime']];
			}
			if($param['seaLinkman'] != ""){
				$where['link_man'] = ['like',"%".$param['seaLinkman']."%"];
			}
			$dayModel = new DaytableModel();
			$rows = $dayModel->getListRows($where,$offset,$limit);
			foreach($rows as $k => $v){
				$rows[$k]['rpt_date'] = date("Y-m-d",$v['rpt_date']);
				$v['is_examine'] == 0 ? $rows[$k]['examine_name']="否" : $rows[$k]['examine_name']="是";
			}
			$total = $dayModel->getCount($where);
			return  ['code'=>1,'msg'=>'表格加载成功','data'=>[
				'rows' => $rows,'total'=>$total
			]];
		}
		$this->assign([
			'departs' => $this->getDepartOpt()
		]);
		return $this->fetch();
	}

	public function dayEdit(){
		$table_id = input("id");
		$table = DB::name("table_day")->where("id",$table_id)->find();
		$company = DB::name("users_company")->where("id",$table['company_id'])->find();
		$buy = DB::name('goods_cate')
			->where('commid','in',explode(",",$company['buy']))
			->field("name,commid")
			->order("id desc")->select();
		$sell = DB::name('goods_cate')
			->where('commid_2','in',explode(",",$company['sell']))
			->field("name,commid_2")
			->order("id desc")->select();
		$this->assign([
			'table' => $table,
			'Company' => $company,
			'Buy' => $buy,
			'Sell' => $sell
		]);
		return $this->fetch('commit/edit_day');
	}

	public function daySee() {
		$table_id = input("id");
		$table = DB::name("table_day")->where("id",$table_id)->find();
		$table['company_name'] = DB::name("users_company")->where("id",$table['company_id'])->value("name");
		$rows = $this->XML2Arr($table['form'])['content'];
		foreach($rows as $k => &$v){
			if($k % 2 == 0){
				switch ($v['countyType']) {
					case '1':$v['countyType_name'] = '县级服务中心';break;
					case '2':$v['countyType_name'] = '乡镇级服务站';break;
					case '3':$v['countyType_name'] = '村级服务站';break;
					default :$v['countyType_name'] = '不详';break;
				}
				$v['buy']['commId'] = $v['commId'];
				$v['buy']['commId_name'] = DB::name("goods_cate")->where('commid',$v['commId'])->value('name');
				$v['buy']['money'] = $v['money'];
				$v['sell']['commId'] = $rows[$k+1]['commId'];
				$v['sell']['money'] = $rows[$k+1]['money'];
				$v['sell']['commId_name'] = DB::name("goods_cate")->where('commid_2',$rows[$k+1]['commId'])->value('name');
			}else{
				unset($rows[$k]);
			}
		}
		$rows = array_merge(array_filter($rows));
		$this->assign([
			'table' => $table,'rows' => $rows
		]);
		return $this->fetch('commit/see_day');
	}

	public function dayDel(){
		$id = input('post.id');
		$info = DB::name('table_day')->where('id',$id)->find();
		if($info['is_commit'] == 1){
			return ['code'=> 0,'msg'=>'删除失败,已提交的报表不能删除'];
		}
		$res = DB::name('table_day')->where('id',$id)->delete();
		if($res !== false){
			return ['code'=> 1,'msg'=>'删除成功'];
		}else{
			return ['code'=> 0,'msg'=>'删除失败'];
		}
	}

	public function dayExamine(){
		$param = input('post.');
		$info = DB::name('table_day')->where('id',$param['id'])->find();
		if($info['is_commit'] == 1){
			return ['code'=> 0,'msg'=>'审核失败,已提交的报表不能审核'];
		}
		$user = DB::name('user')->where('id',session('id'))->value('real_name');
		$param['examine_man'] = $user;
		$res = DB::name('table_day')->where('id',$param['id'])->update($param);
		if($res !== false){
			return ['code'=>1,'msg'=>'审核成功'];
		}else{
			return ['code'=>0,'msg'=>'审核失败'];
		}
	}

	public function getDayFormCT() {
		$table_id = input("post.table_id");
		$table = DB::name("table_day")->where("id",$table_id)->find();
		$rows = $this->XML2Arr($table['form'])['content'];
		foreach($rows as $k => &$v){
			if($k % 2 == 0){
				$v['serviceStationCommodity'][] = [
					'commId' => $v['commId'],
					'money' => $v['money']
				];
				$v['serviceStationCommodity'][] = [
					'commId' => $rows[$k+1]['commId'],
					'money' => $rows[$k+1]['money']
				];
			}else{
				unset($rows[$k]);
			}
		}
		$rows = array_merge(array_filter($rows));
		return ['code'=>1,'msg'=>'','data'=>$rows];
	}
	#-< company >---------------------------------------------------------------
	public function companyList() {
		if($this->request->isPost()){
			$param = input('post.');
			$limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
			$where = [];
			if($param['seaDepart'] != ''){
				$where['depart_id'] = $param['seaDepart'];
			}
			if($param['seaEnterName'] != ""){
				$where['enter_name'] = ['like',"%".$param['seaEnterName']."%"];
			}
			$CapitalModel = new CapitaltableModel();
			$rows = $CapitalModel->getListRows($where,$offset,$limit);
			foreach($rows as $k => $v){
				if($v['is_commit'] == 0){
					$rows[$k]['is_commit_name'] = "未提交";
				}else{
					$rows[$k]['is_commit_name'] = "已提交";
				}
			}
			$total = $CapitalModel->getCount($where);
			return  ['code'=>1,'msg'=>'表格加载成功','data'=>[
				'rows' => $rows,'total'=>$total
			]];
		}
		$this->assign([
			'departs' => $this->getDepartOpt()
		]);
		return $this->fetch();
	}

	public function companyListDel(){
		$id = input('post.id');
		$info = DB::name('table_capital')->where('id',$id)->find();
		if($info['is_commit'] != 0){
			return ['code'=> 0,'msg'=>'删除失败,已提交的表不能删除'];
		}
		$res = DB::name('table_capital')->where('id',$id)->delete();
		if($res !== false){
			return ['code'=> 1,'msg'=>'删除成功'];
		}else{
			return ['code'=> 0,'msg'=>'删除失败'];
		}
	}

	public function companyListEdit() {
		$this->assign([
			'id' => input("id")
		]);
		return $this->fetch('commit/edit_capital');
	}

	public function getForm_company() {
		$id = input('post.id');
		$ct = DB::name('table_capital')->where('id',$id)->value('content');
		$form = $this->XML2Arr($ct);
		$year = date("Y",time());
		$moneyLimit = DB::name('capital_mgr')->where([
			'depart_id' => $form['departId'],'year' => $year
		])->value("capital");
		if($moneyLimit == ''){
			return [
				'code'=>0,'msg'=>'请先设置今年的资金',
				'data'=>$form,'moneyLimit'=>$moneyLimit
			];
		}
		return ['code'=>1,'msg'=>'','data'=>$form,'moneyLimit'=>$moneyLimit];
	}

	#-< project >---------------------------------------------------------------
	public function projectList() {
		if($this->request->isPost()){
			$param = input('post.');
			$where = ['is_commit'=>1];
			if($param['seaDepart'] != ''){
				$where['depart_id'] = $param['seaDepart'];
			}else{
				return ['code'=>0,'msg'=>'查询条件不全','data'=>''];
			}
			if($param['seaEnterName'] != ""){
				$where['enter_name'] = ['like',"%".$param['seaEnterName']."%"];
			}else{
				return ['code'=>0,'msg'=>'查询条件不全','data'=>''];
			}
			$companys = DB::name('table_capital')->where($where)->select();
			$rows = $this->getProjectRows($companys);
			return  ['code'=>1,'msg'=>'表格加载成功','data'=>[
				'rows' => $rows
			]];
		}
		$this->assign([
			'departs' => $this->getDepartOpt()
		]);
		return $this->fetch();
	}

	public function getProjectRows($companys) {
		$rows = [];
		foreach($companys as $v){
			$data = $this->XML2Arr($v['content']);
			foreach($data['fundAppropriateData'] as $va){
				$res = [];
				$res['depart_id'] = $data['departId'];
				$res['depart_name'] = $data['departName'];
				$res['link_man'] = $data['linkMan'];
				$res['link_type'] = $data['linkType'];
				$res['enter_name'] = $data['enterName'];
				$res['enter_name'] = $data['enterName'];
				switch ($va['projectType']) {
					case '1':
						$res['project_type'] = "公共服务体系";break;
					case '2':
						$res['project_type'] = "物流配送体系";break;
					case '3':
						$res['project_type'] = "农村产品上行";break;
					case '4':
						$res['project_type'] = "农村电商培训";break;
					default:
						$res['project_type'] = "不详";break;
				}
				$res['project_name'] = $va['projectName'];
				$res['all'] = $va['allocatedMoney'];
				$res['un'] = $va['unAllocatedMoney'];
				$res['money_ratio'] = $va['moneyRatio'];
				$rows[] = $res;
			}
		}
		return $rows;
	}

	#-< asset >-----------------------------------------------------------------
	public function Asset() {
		if($this->request->isPost()){
			$param = input("post.");
			$limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
			$where = [];
			if($param['depart_id'] != ''){
				$where['depart_id'] = $param['depart_id'];
			}
			if($param['s_time'] != '' && $param['e_time'] != ''){
				$where['rpt_date'] = ['between',[$param['s_time']/1000,$param['e_time']/1000]];
			}
			if($param['link_man'] != ''){
				$where['link_man'] = ['like',"%".$param['link_man']."%"];
			}
			$order = "rpt_date desc";
			$AssetModel = new AssettableModel();
			$return['rows'] = $AssetModel->getListRows($where,$offset,$limit,$order);
			$return['total'] = $AssetModel->getCount($where);
			foreach($return['rows'] as &$v){
				$v['rpt_date'] = date("Y年m月",$v['rpt_date']);
				if($v['is_commit'] == 1){
					$v['is_commit_name'] = "已提交";
				}else{
					$v['is_commit_name'] = "未提交";
				}
				$v['depart_name'] = DB::name("department")->where('id',$v['depart_id'])->value("name");
			}
			return ['code'=>1,'msg'=>'加载成功','data'=>$return];
		}
		$this->assign([
			'departs' => $this->getDepartOpt()
		]);
		return $this->fetch();
	}

	public function AssetSee() {
		$table_id = input('table_id');
		$table = DB::name("table_asset")->where("id",$table_id)->find();
		$depart = DB::name("department")->where('id',$table['depart_id'])->find();
		$rows = $this->XML2Arr($table['content']);
		foreach($rows as &$row){
			if($row['is_del'] == 1){
				$row['is_del'] = "<span class='span-danger'>已删除</span>";
			}else{
				$row['is_del'] = "<span class='span-primary'>未删除</span>";
				$row['del_remark'] = "";
			}
		}
		$this->assign([
			'table' => $table,'rows' => $rows,'depart' => $depart
		]);
		return $this->fetch("commit/see_asset");
	}

	#-< webshop >---------------------------------------------------------------
	public function webShop() {
		if($this->request->isPost()){
			$param = input("post.");
			$limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
			$where = [];
			if($param['depart_id'] != ''){
				$where['depart_id'] = $param['depart_id'];
			}
			if($param['s_time'] != '' && $param['e_time'] != ''){
				$where['rpt_date'] = ['between',[$param['s_time']/1000,$param['e_time']/1000]];
			}
			if($param['link_man'] != ''){
				$where['link_man'] = ['like',"%".$param['link_man']."%"];
			}
			$Model = new WebshoptableModel();
			$return['rows'] = $Model->getListRows($where,$offset,$limit);
			foreach($return['rows'] as &$v){
				$v['rpt_date'] = date("Y年m月",$v['rpt_date']);
				$v['company_name'] = DB::name("users_company")
					->where("id",$v['company_id'])->value("name");
				if($v['is_commit'] == 1){
					$v['is_commit_name'] = "已提交";
				}else{
					$v['is_commit_name'] = "未提交";
				}
			}
			$return['total'] = $Model->getCount($where);
			return ['code'=>1,'msg'=>'表格加载成功','data'=>$return];
		}
		$this->assign([
			'departs' => $this->getDepartOpt()
		]);
		return $this->fetch();
	}

	public function WebshopEdit() {
		$this->assign([
			'table_id' => input("table_id")
		]);
		return $this->fetch('commit/edit_webshoptable');
	}

	public function WebshopDel() {
		$id = input('post.id');
		$info = DB::name('table_webshop')->where('id',$id)->find();
		if($info['is_commit'] != 0){
			return ['code'=> 0,'msg'=>'删除失败,已提交的表不能删除'];
		}
		$res = DB::name('table_webshop')->where('id',$id)->delete();
		if($res !== false){
			return ['code'=> 1,'msg'=>'删除成功'];
		}else{
			return ['code'=> 0,'msg'=>'删除失败'];
		}
	}

	public function getWebshopForm() {
		$table_id = input("post.table_id");
		$table = DB::name("table_webshop")->where('id',$table_id)->find();
		$table['content'] = $this->XML2Arr($table['content']);
		$table['rpt_date'] = $table['rpt_date']*1000;
		return ['code'=>1,'msg'=>'success','data'=>$table];
	}


	public function webshopCommit() {
		$table_id = input("post.id");
		$info = DB::name("table_webshop")->where('id',$table_id)->find();
		if($info['is_commit'] == 1){
			return ['code'=>0,'msg'=>'该报表已经提交，请勿重复提交'];
		}
		DB::startTrans();
		try {
			# 修改状态
			DB::name("table_webshop")->where('id',$table_id)->update(['is_commit' => 1]);
			# 写入统计数据
			// print_r($info);die;
			$tableCt = $this->XML2Arr($info['content']);
			foreach($tableCt as $v){
				$data = $v;
				$data['depart_id'] = $info['depart_id'];
				$data['depart_name'] = $info['depart_name'];
				$data['rpt_date'] = $info['rpt_date'];
				$data['create_uid'] = $info['create_uid'];
				$data['company_id'] = $info['company_id'];
				DB::name("statistics_webshop")->insert($data);
				$webshop = DB::name("webshop")->where([
					'name' => $v['webshop_name'],
					'url' => $v['webshop_url'],
					'remark' => $v['webshop_remark']
				])->find();
				$sum_pro = $webshop['sum_pro'] + $v['pro_num'];
				$sum_sell = $webshop['sum_sell'] + $v['sales_amount'];
				DB::name("webshop")->where([
					'name' => $v['webshop_name'],
					'url' => $v['webshop_url'],
					'remark' => $v['webshop_remark']
				])->update([
					'sum_pro' => $sum_pro,
					'sum_sell' => $sum_sell
				]);
			}
			DB::commit();
			return ['code'=>1,'msg'=>'提交成功'];
		} catch (\Exception $e) {
			DB::rollback();
			return ['code'=>0,'msg'=>'提交失败'];
		}
	}
}
